import React, { useState } from "react";
import { View, Text, Picker } from "@tarojs/components";
import { AtInput, AtRadio, AtToast, AtTextarea } from "taro-ui";
import Taro, { getCurrentInstance, useDidShow } from "@tarojs/taro";
import _ from "lodash";
import dayjs from "dayjs";

import api from "@api/api.js";
import Modal from "../../components/modal";
import { formModel, timePicker } from "./helper";
import "./style.less";

export default () => {
  const [toast, setToast] = useState({ text: "", isOpened: false });
  const [diagnosisSchemesId, setDiagnosisSchemesId] = useState(""); //方案id
  const [patientId, setPatientId] = useState("");
  const [form, setForm] = useState(_.cloneDeep(formModel));
  const [isOpenedHuan, setIsOpenedHuan] = useState(false); // 患者来源弹窗
  const [huanSr, setHuanSr] = useState([]); // 患者来源Option
  const [huanSrFm, setHuanSrFm] = useState({
    patientSource: "",
    patientRemark: "",
  }); // 患者来源弹窗表单模型
  const [isOpenedHuanIf, setIsOpenedHuanIf] = useState(false); // 患者信息弹窗
  const [huanIf, setHuanIf] = useState({});
  const [huanIfFm, sethuanIfFm] = useState({
    name: "",
    phoneNumber: "",
    patientId: "",
  });

  const [schemesDtl, setSchemesDtl] = useState({
    name: "",
    gender: "",
    age: "",
    status: "",
    totalNumberOfDiag: "",
    lastDiagTime: "",
  });
  useDidShow(() => {
    getSysParam();
    const params = getCurrentInstance().router.params;
    const { dateTime, id, diagnosisSchemesId } = params;
    if (id) {
      Taro.setNavigationBarTitle({
        title: "编辑日程",
      });
      syncDtl(id);
    } else {
      // 新增
      Taro.setNavigationBarTitle({
        title: "创建日程",
      });
      if (diagnosisSchemesId) {
        setDiagnosisSchemesId(diagnosisSchemesId);
        getSchemesDtl(diagnosisSchemesId);
      }
      const dateTimeFmt = dayjs(dateTime);
      form.startTime = dateTimeFmt;
      form.endTime = dateTimeFmt.add(30, "minute");
    }
    setForm({ ...form });
  });

  // 获取关联方案
  const getSchemesDtl = async (id) => {
    const { data } = await api.getSchemesDtl(id);
    setPatientId(data.patientDTO.patientId);
    setHuanIf(data.patientDTO);
    setSchemesDtl({ ...data });
  };

  // 编辑的时候，还原详情
  const syncDtl = async (id) => {
    const { data } = await api.getSchedule({ id: id });
    // 同步一层表单
    const formModel = {
      diagnosisSchemesId: data.diagnosisSchemesId, //关联的方案id 必填(由患者信息生成)
      endTime: data.todayDate + " " + data.endTime, // 结束时间 必填
      id: data.id, //日程id
      patientId: data.patientDTO.patientId, // 患者id
      patientSource: data.patientSource, // 患者来源
      patientRemark: data.patientRemark, // 患者来源备注
      remark: data.remark, // 备注
      startTime: data.todayDate + " " + data.startTime, // 开始时间 必填
      todayDate: data.todayDate, // 日期 必填
    };
    setForm({ ...formModel });
    setPatientId(data.patientDTO.patientId);
    // 有方案的情况
    if (data.diagnosisSchemesId) {
      setDiagnosisSchemesId(data.diagnosisSchemesId);
      getSchemesDtl(data.diagnosisSchemesId);
    }
    // 同步二层表单--患者信息
    const { patientDTO } = data;
    const huanData = {
      patientId: patientDTO.patientId,
      name: patientDTO.name,
      phoneNumber: patientDTO.phoneNumber,
    };

    setHuanIf({ ...huanData });
    sethuanIfFm({ ...huanData });

    // 同步二层表单--患者来源
    const patientDate = {
      patientRemark: data.patientRemark,
      patientSource: data.patientSource,
    };
    setHuanSrFm({ ...patientDate });
  };

  // 获取数据字典
  const getSysParam = async () => {
    // patient_source
    const {
      data: { patient_source },
    } = await api.getSysParam(["patient_source"]);
    const res = patient_source.map((item) => ({
      label: item.paramDesc,
      value: item.paramCode,
    }));
    setHuanSr(res);
  };

  // 开始和结束日期变化
  const onDateChange = (val, type) => {
    const [hIndex, mIndex] = val.detail.value;
    const params = getCurrentInstance().router.params;
    const { dateTime, id } = params;
    let ymd;
    if (id) {
      ymd = dayjs(form.todayDate);
    } else {
      ymd = dayjs(dateTime);
    }
    const yearMd = dayjs(ymd).format("YYYY-MM-DD");
    const fullTime =
      yearMd + " " + timePicker[0][hIndex] + ":" + timePicker[1][mIndex];
    form[type] = dayjs(fullTime);

    setForm({ ...form });
  };

  // 患者来源弹窗结束
  const okCallHuan = () => {
    setIsOpenedHuan(false);
    const res = { ...form, ...huanSrFm };
    setForm({ ...res });
  };

  // 患者来源弹窗确定
  const cancelCallHuan = () => {
    setIsOpenedHuan(false);
  };

  // 弹窗关闭
  const onCloseMd = (type) => {
    if (type === "huan") {
      setIsOpenedHuan(false);
    } else if (type === "huanIf") {
      setIsOpenedHuanIf(false);
    }
  };

  // 患者信息弹窗确定按钮
  const okCallHuanIf = async () => {
    const { data, code, errorMessage } = await api.saveSchedulePatientInfo(
      huanIfFm
    );

    if (code == 200) {
      // 同步表单到患者信息form
      huanIfFm.patientId = data;
      setHuanIf({ ...huanIfFm });
      sethuanIfFm({ ...huanIfFm });
      setIsOpenedHuanIf(false);
      setPatientId(data);
      // 同步表单到form
      setForm({ ...form, patientId: data });
    } else {
      setToast({
        text: errorMessage,
        isOpened: true,
      });
    }
  };

  // 患者信息弹窗取消按钮
  const cancelCallHuanIf = () => {
    console.log(form);
    setIsOpenedHuanIf(false);
  };

  // 患者来源弹窗表单 来源
  const handlePSourceChange = (e) => {
    huanSrFm.patientSource = e;
    setHuanSrFm({ ...huanSrFm });
  };

  // 患者来源弹窗表单 备注
  const handlePSRemarkChange = (e) => {
    huanSrFm.patientRemark = e;
    console.log(e);
    sethuanIfFm({ ...huanSrFm });
  };

  // 患者信息 姓名
  const handleHFnameChange = (e) => {
    huanIfFm.name = e;
    sethuanIfFm({ ...huanIfFm });
  };

  // 患者信息 手机
  const handleHFphoneNumberChange = (e) => {
    huanIfFm.phoneNumber = e;
    sethuanIfFm({ ...huanIfFm });
  };

  // 备注输入事件
  const handleRmarkChange = (e) => {
    console.log(e);
    form.remark = e;
    setForm({ ...form });
  };

  // 表单提交按钮
  const onSubmitForm = async () => {
    console.log(patientId);
    const params = _.cloneDeep(form);
    params.startTime = dayjs(form.startTime).format("HH:mm");
    params.endTime = dayjs(form.endTime).format("HH:mm");
    params.todayDate = dayjs(form.startTime).format("YYYY-MM-DD");
    params.diagnosisSchemesId = diagnosisSchemesId;
    params.patientId = patientId;
    !params.id && delete params.id;

    let message;

    if (dayjs(form.endTime).isBefore(dayjs(form.startTime))) {
      message = "结束时间要大于开始时间";
    }
    if (message) {
      setToast({
        text: message,
        isOpened: true,
      });
    } else {
      const { code, errorMessage } = await api.saveSchedule(params);
      if (code == 200) {
        setToast({
          text: "保存成功",
          isOpened: true,
          onClose: () => {
            Taro.navigateBack({
              delta: 1,
            });
          },
        });
      } else {
        setToast({
          text: errorMessage,
          isOpened: true,
        });
      }
    }
  };
  // 删除日程
  const delScheduleById = async () => {
    if (form.id) {
      const { code } = await api.delScheduleById({ id: form.id });
      if (code == 200) {
        setToast({
          text: "删除成功",
          isOpened: true,
          onClose: () => {
            Taro.navigateBack({
              delta: 1,
            });
          },
        });
      }
    } else {
      Taro.navigateBack({
        delta: 1,
      });
    }
  };

  return (
    <View className="bgBox">
      <AtToast {...toast}></AtToast>
      <View className="listBox">
        <View className="box">
          <View className="item borderBottom">
            <Text className="label">医生</Text>
            <View className="extra-text-arrow">
              <Text className="extra-text">我</Text>
              <View className="icon" />
            </View>
          </View>
          <View className="item borderBottom">
            <Text className="label">开始时间</Text>
            <Picker
              mode="multiSelector"
              range={timePicker}
              onChange={(e) => {
                onDateChange(e, "startTime");
              }}
            >
              <View className="extra-text-arrow">
                <Text className="extra-text">
                  {dayjs(form.startTime).format("HH:mm")}
                </Text>
                <View className="at-icon at-icon-chevron-right icon" />
              </View>
            </Picker>
          </View>
          <View className="item borderBottom">
            <Text className="label">结束时间</Text>
            <Picker
              mode="multiSelector"
              range={timePicker}
              onChange={(e) => {
                onDateChange(e, "endTime");
              }}
            >
              <View className="extra-text-arrow">
                <Text className="extra-text">
                  {dayjs(form.endTime).format("HH:mm")}
                </Text>
                <View className="at-icon at-icon-chevron-right icon" />
              </View>
            </Picker>
          </View>
          <View className="item borderBottom">
            <Text className="label">患者信息</Text>
            <View
              className="extra-text-arrow"
              onClick={() => {
                !diagnosisSchemesId ? setIsOpenedHuanIf(true) : "";
              }}
            >
              <Text className="extra-text">
                {huanIf.name ? huanIf.name : "请填写患者信息"}
                {huanIf?.phoneNumber}
              </Text>
              <View
                className={
                  !diagnosisSchemesId
                    ? "at-icon at-icon-chevron-right icon"
                    : "icon"
                }
              />
            </View>
          </View>
          <View className="item borderBottom">
            <Text className="label">患者来源</Text>
            <View
              className="extra-text-arrow"
              onClick={() => {
                setIsOpenedHuan(true);
              }}
            >
              <Text className="extra-text">
                {(() => {
                  const res = huanSr.filter(
                    (item) => item.value === form.patientSource
                  )[0]?.label;
                  return res ? res : "请选择患者来源";
                })()}
              </Text>
              <View
                className="at-icon at-icon-chevron-right"
                style={{ width: "30rpx", height: "30rpx" }}
              />
            </View>
          </View>

          {diagnosisSchemesId && (
            <>
              <View
                className="item borderBottom"
                style={{ borderBottom: "none" }}
              >
                <Text className="label">关联方案</Text>
              </View>
              <View className="fangan">
                <View className="two">
                  <Text className="num">
                    第{schemesDtl.totalNumberOfDiag}次会诊
                  </Text>
                  <Text className="time">{schemesDtl.lastDiagTime}</Text>
                </View>
                <View className="hr" />
                <View className="three">
                  <Text>
                    手术方案：{" "}
                    {schemesDtl.surgicalTypes &&
                      schemesDtl.surgicalTypes.map((item) => {
                        return item;
                      })}
                  </Text>
                </View>
              </View>
            </>
          )}
          <View className="remark">
            <View className="label">备注</View>
            <View>
              <AtTextarea
                placeholder="请输入备注内容"
                count={false}
                placeholderClass="font"
                value={form.remark}
                onChange={handleRmarkChange}
              ></AtTextarea>
            </View>
          </View>
        </View>
        <View className="saveFooter at-row">
          <View className="at-col">
            <View className="clearBtn" onClick={delScheduleById}>
              {form.id ? "删除" : "取消"}
            </View>
          </View>
          <View className="at-col">
            <View className="saveBtn" onClick={onSubmitForm}>
              确认
            </View>
          </View>
        </View>
      </View>
      {isOpenedHuan && (
        <Modal
          isOpened={isOpenedHuan}
          title="患者来源"
          okCall={okCallHuan}
          cancelCall={cancelCallHuan}
          onClose={() => {
            onCloseMd("huan");
          }}
        >
          <View className="huanzhe-modal input">
            <AtRadio
              name="huanSr"
              options={huanSr}
              value={huanSrFm.patientSource}
              onClick={handlePSourceChange}
            />
            <View className="fontBold">备注</View>
            <AtInput
              name="huanSrName"
              placeholder="请输入来源备注"
              value={huanSrFm.patientRemark}
              onChange={handlePSRemarkChange}
            />
          </View>
        </Modal>
      )}

      {/* isOpenedHuanIf */}
      {isOpenedHuanIf && (
        <Modal
          isOpened={isOpenedHuanIf}
          title="患者信息"
          okCall={okCallHuanIf}
          cancelCall={cancelCallHuanIf}
          onClose={() => {
            onCloseMd("huanIf");
          }}
        >
          <View className="huanzhe-modal input">
            <View className="fontBold">患者姓名</View>
            <AtInput
              name="huanName"
              placeholder="请输入患者姓名"
              value={huanIfFm.name}
              onChange={handleHFnameChange}
            />

            <View className="fontBold">患者手机号</View>
            <AtInput
              name="huanPhone"
              placeholder="请输入患者手机号"
              value={huanIfFm.phoneNumber}
              onChange={handleHFphoneNumberChange}
            />
          </View>
        </Modal>
      )}
    </View>
  );
};
